'use strict';

const { Controller } = require('egg');
const bcrypt = require('bcrypt');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    ctx.validate({
      id: { type: 'number' },
      password: { type: 'string' },
    });
    const { id, password } = ctx.request.body;
    const result = await ctx.model.User.findByPk(id);
    if (result) {
      const res = bcrypt.compareSync(password, result.password);
      if (res) {
        ctx.session.id = id;
        ctx.status = 204;
      } else {
        ctx.status = 401;
      }
    } else {
      ctx.status = 404;
    }
  }

  async signup() {
    const { ctx } = this;
    ctx.validate({
      name: { type: 'string', max: 29 },
      password: { type: 'string' },
    });
    const { name, password } = ctx.request.body;
    const hash = bcrypt.hashSync(password, 10);
    if (hash) {
      const user = await ctx.model.User.create({ name, password: hash });
      if (user) {
        ctx.status = 201;
        ctx.session.id = user.id;
        ctx.body = user;
        // do not return the hash value of password
        ctx.body.password = undefined;
      } else {
        ctx.throw(500, 'ctx.model.User.create() return nothing');
      }
    } else {
      ctx.throw(500, 'bcrypt.hash() return nothing');
    }
  }
}

module.exports = UserController;
